package com.xcjh.module_ad.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.VideoController
import com.google.android.gms.ads.VideoOptions
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdOptions
import com.google.android.gms.ads.nativead.NativeAdView
import com.xcjh.base_lib.base.activity.BaseActivity
import com.xcjh.base_lib.utils.loge
import com.xcjh.base_lib.utils.myToast
import com.xcjh.module_ad.databinding.AdActivityNativeBinding
import com.xcjh.module_ad.databinding.AdUnifiedBinding

/** admob原生广告 */
class AdNativeActivity : BaseActivity() {
    private val TAG = "AdNativeActivity"
    private val ADMOB_AD_UNIT_ID = "ca-app-pub-3940256099942544/2247696110"
    private lateinit var mainActivityBinding: AdActivityNativeBinding
    private var currentNativeAd: NativeAd? = null
    private lateinit var adLoader: AdLoader
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainActivityBinding = AdActivityNativeBinding.inflate(layoutInflater)
        setContentView(mainActivityBinding.root)
        // Initialize the Mobile Ads SDK.
        // MobileAds.initialize(this) {}
        mainActivityBinding.refreshButton.setOnClickListener {
            refreshAd()
        }
        refreshAd()
    }

    /**
     *根据布尔参数创建对新原生广告的请求，并在成功返回时调用相应的“填充”方法.
     */
    @SuppressLint("MissingPermission")
    private fun refreshAd() {
        mainActivityBinding.refreshButton.isEnabled = false
        adLoader = AdLoader.Builder(this, ADMOB_AD_UNIT_ID)
            .forNativeAd { nativeAd ->
                // 如果这个回调发生在活动被销毁之后，你必须调用销毁并返回，否则你可能会发生内存泄漏
                val activityDestroyed: Boolean = isDestroyed
                if (activityDestroyed || isFinishing || isChangingConfigurations) {
                    nativeAd.destroy()
                    return@forNativeAd
                }
                // 当你完成旧广告时，你必须调用销毁它们,否则你会发生内存泄漏
                currentNativeAd?.destroy()
                currentNativeAd = nativeAd
                currentNativeAd?.setMuteThisAdListener {
                   // 接收广告静音的确认信息
                }
                val unifiedAdBinding = AdUnifiedBinding.inflate(layoutInflater)
                populateNativeAdView(nativeAd, unifiedAdBinding)
                mainActivityBinding.adFrame.removeAllViews()
                mainActivityBinding.adFrame.addView(unifiedAdBinding.root)
                if (adLoader.isLoading) {
                    // AdLoader 仍在加载广告.
                    // 期待更多 adLoaded 或 onAdFailedToLoad 回调
                    "AdLoader 仍在加载广告。".loge("====")
                } else {
                    // AdLoader 已完成加载广告。
                    "AdLoader 已完成加载广告。".loge("====")
                }
            }
            .withAdListener(object : AdListener() {
                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    val error =
                        "domain: ${loadAdError.domain}, code: ${loadAdError.code}, message: ${loadAdError.message}"
                    mainActivityBinding.refreshButton.isEnabled = true
                    myToast("加载原生广告失败，出现错误 $error")
                }
            })
            .withNativeAdOptions(
                NativeAdOptions.Builder().setRequestCustomMuteThisAd(true).setVideoOptions(
                    VideoOptions.Builder()
                        .setStartMuted(mainActivityBinding.startMutedCheckbox.isChecked).build()
                ).build()
            )
            .build()
           //.loadAds(AdRequest.Builder().build(),2)
        adLoader.loadAds(AdRequest.Builder().build(), 2)

        mainActivityBinding.videostatusText.text = ""
    }
    /**
     * 使用来自给定 [NativeAd] 的数据填充 [NativeAdView] 对象。
     * 填充原生广告视图
     * @param nativeAd 包含广告资源的对象
     * @param unifiedAdBinding 以 NativeAdView 为根视图的布局的绑定对象
     */
    private fun populateNativeAdView(nativeAd: NativeAd, unifiedAdBinding: AdUnifiedBinding) {
        val nativeAdView = unifiedAdBinding.root

        // 设置媒体视图.
        nativeAdView.mediaView = unifiedAdBinding.adMedia

        // 设置其他广告资源.
        nativeAdView.headlineView = unifiedAdBinding.adHeadline
        nativeAdView.bodyView = unifiedAdBinding.adBody
        nativeAdView.callToActionView = unifiedAdBinding.adCallToAction
        nativeAdView.iconView = unifiedAdBinding.adAppIcon
        nativeAdView.priceView = unifiedAdBinding.adPrice
        nativeAdView.starRatingView = unifiedAdBinding.adStars
        nativeAdView.storeView = unifiedAdBinding.adStore
        nativeAdView.advertiserView = unifiedAdBinding.adAdvertiser

        // 标题和媒体内容保证在每个 UnifiedNativeAd 中.
        unifiedAdBinding.adHeadline.text = nativeAd.headline
        nativeAd.mediaContent?.let { unifiedAdBinding.adMedia.mediaContent = it }

        // 这些资产不能保证在每个 UnifiedNativeAd 中都有，因此在尝试显示它们之前进行检查很重要.
        if (nativeAd.body == null) {
            unifiedAdBinding.adBody.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adBody.visibility = View.VISIBLE
            unifiedAdBinding.adBody.text = nativeAd.body
        }

        if (nativeAd.callToAction == null) {
            unifiedAdBinding.adCallToAction.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adCallToAction.visibility = View.VISIBLE
            unifiedAdBinding.adCallToAction.text = nativeAd.callToAction
        }

        if (nativeAd.icon == null) {
            unifiedAdBinding.adAppIcon.visibility = View.GONE
        } else {
            unifiedAdBinding.adAppIcon.setImageDrawable(nativeAd.icon?.drawable)
            unifiedAdBinding.adAppIcon.visibility = View.VISIBLE
        }

        if (nativeAd.price == null) {
            unifiedAdBinding.adPrice.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adPrice.visibility = View.VISIBLE
            unifiedAdBinding.adPrice.text = nativeAd.price
        }

        if (nativeAd.store == null) {
            unifiedAdBinding.adStore.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adStore.visibility = View.VISIBLE
            unifiedAdBinding.adStore.text = nativeAd.store
        }

        if (nativeAd.starRating == null) {
            unifiedAdBinding.adStars.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adStars.rating = nativeAd.starRating!!.toFloat()
            unifiedAdBinding.adStars.visibility = View.VISIBLE
        }

        if (nativeAd.advertiser == null) {
            unifiedAdBinding.adAdvertiser.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adAdvertiser.text = nativeAd.advertiser
            unifiedAdBinding.adAdvertiser.visibility = View.VISIBLE
        }

        // 此方法告诉 Google 移动广告 SDK 您已完成使用此原生广告填充原生广告视图.
        nativeAdView.setNativeAd(nativeAd)

        // 获取广告的视频控制器。将始终提供一个，即使广告没有视频资源.
        val mediaContent = nativeAd.mediaContent
        val vc = mediaContent?.videoController

        // 更新用户界面以说明此广告是否包含视频资源.
        if (vc != null && mediaContent.hasVideoContent()) {
            //创建一个新的 VideoLifecycleCallbacks 对象并将其传递给 VideoController。当视频生命周期中发生事件时，VideoController 将调用此对象的方法.
            vc.videoLifecycleCallbacks = object : VideoController.VideoLifecycleCallbacks() {
                override fun onVideoEnd() {
                    // 发布商应允许原生广告完成视频播放，然后再在同一 UI 位置刷新或替换为另一个广告
                    mainActivityBinding.refreshButton.isEnabled = true
                    mainActivityBinding.videostatusText.text = "视频状态: 视频播放已结束."
                    super.onVideoEnd()
                }
            }
        } else {
            mainActivityBinding.videostatusText.text = "视频状态: 广告不包含视频asset."
            mainActivityBinding.refreshButton.isEnabled = true
        }
    }

    override fun onDestroy() {
        currentNativeAd?.destroy()
        super.onDestroy()
    }
}